//
//  SettingNameHeadViewController.m
//  shuiyun
//
//  Created by 马田成 on 2017/9/8.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "SettingNameHeadViewController.h"
#import "MyTabBarController.h"

#import "STPhotoKitController.h"
#import "UIImagePickerController+ST.h"
#import "UIButton+AddAction.h"
#import "ICN_HeadImageSelView.h"


@interface SettingNameHeadViewController ()<UITextFieldDelegate,UIImagePickerControllerDelegate,STPhotoKitDelegate,UINavigationControllerDelegate>
{
    
    UIView *grayView;
    
}
@property (weak, nonatomic) IBOutlet UIButton *headImg;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (nonatomic, strong) MyTabBarController *tabBarController;
@property (nonatomic, strong) ICN_HeadImageSelView *changeHeadImageView;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSData *imageData;

@end

@implementation SettingNameHeadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.nameTF.delegate = self;
    _headImg.layer.cornerRadius = 44.0f;
    _headImg.layer.masksToBounds = YES;
    
    
    // Do any additional setup after loading the view from its nib.
}
- (IBAction)loginClick:(UIButton *)sender {
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在上传...";
    //是否有遮罩
    hud.dimBackground = YES;
    

    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];

    [productParams setValue:self.nameTF.text forKey:@"username"];
    [productParams setValue:self.password forKey:@"password"];
    [productParams setValue:self.phone forKey:@"phone"];
//    [productParams setValue:self.phoneID forKey:@"userid"];

    
    /*方式一：使用NSData数据流传图片*/
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/plain",
                                                         @"text/javascript",
                                                         @"text/json",
                                                         @"text/html",
                                                         @"image/jpeg", nil];
    [manager POST:hometRegisterRegister parameters:productParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
       
        
        if (self.image) {
            
            self.imageData = UIImageJPEGRepresentation(self.image,0.005);
        }else {
        
            self.imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"添加头像"],0.005);
            
        }
        
        
        //压缩图片
        
        //拼接图片名称+时间确保不重复命名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *imageFileName = [NSString stringWithFormat:@"%@.jpg", [formatter stringFromDate:[NSDate date]]];
        // 测试输出文件名
        
        //上传图片，以文件流的格式sdf
        
        //        [formData appendPartWithFileData:UIImageJPEGRepresentation([UIImage imageNamed:@"1"], 5.0) name:@"image1" fileName:@"1.jpg" mimeType:@"image/jpeg"];
        
        [formData appendPartWithFileData:_imageData name:@"titlepic" fileName:imageFileName mimeType:@"image/JPG"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *strtmp = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *requestTmp = [NSString stringWithString: strtmp];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];  //解析
        NSLog(@"+++>%@", resultDic);
        NSLog(@"--->%@", resultDic[@"msg"]);
        [hud removeFromSuperview];
        if ([[resultDic objectForKey:@"code"]intValue]==1) {
            
            NSMutableDictionary *dic = [resultDic objectForKey:@"data"];
            
            
            [PublicFunction saveConfig:[dic objectForKey:@"token"] forKey:@"token"];
            [PublicFunction saveConfig:[dic objectForKey:@"userid"] forKey:@"userid"];
            UINavigationBar *bar = [UINavigationBar appearance];
            
            
            bar.barStyle=UIBarStyleBlackTranslucent;
            
            //设置显示的颜色
            
            bar.barTintColor =[ZJCModel colorWithString:@"3F87F6"];
            
            //设置字体颜色
            
            bar.tintColor = [UIColor whiteColor];
            
            
            [bar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
            MyTabBarController *barController = [[MyTabBarController alloc] init];
            // TAB BAR
            
            [self presentViewController:barController animated:YES completion:nil];
            

            
        }
        
        else {
            
            [PublicFunction showAlert:nil message:[resultDic objectForKey:@"msg"] duration:5.0f];
            
        }
        
        
        
        
       
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
        [hud removeFromSuperview];
        NSLog(@"--->%@", error);
    }];
    

   
    
}
- (IBAction)headerImgClick:(UIButton *)sender {
    
    grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
    grayView.backgroundColor = [UIColor colorWithRed:0 / 255.0f green:0 / 255.0f blue:0 / 255.0f alpha:0.2];
    
    [[UIApplication sharedApplication].keyWindow addSubview:grayView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView)];
    [grayView addGestureRecognizer:tapGesture];
    
    [grayView addSubview:self.changeHeadImageView];
    [self.changeHeadImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(DEF_SCREEN_WIDTH, 160));
    }];
    
    self.changeHeadImageView.layer.cornerRadius = 8;
    [self.changeHeadImageView.takePhotoButton addAction:^(NSInteger tag) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
        [grayView removeFromSuperview];
        if ([controller isAvailableCamera] && [controller isSupportTakingPhotos]) {
            [controller setDelegate:self];
            [self presentViewController:controller animated:YES completion:nil];
        }else {
            NSLog(@"%s %@", __FUNCTION__, @"相机权限受限");
        }
    }];
    [self.changeHeadImageView.localAlbumButton addAction:^(NSInteger tag) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        [controller setDelegate:self];
        [grayView removeFromSuperview];
        if ([controller isAvailablePhotoLibrary]) {
            [self presentViewController:controller animated:YES completion:nil];
        }
    }];
    [self.changeHeadImageView.closeViewButton addAction:^(NSInteger tag) {
        [self dismissContactView];
    }];

    
    
}
#pragma mark ----------------------- 相册／相机 ---------------------

- (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage
{
    // [self.imageButton setImage:resultImage forState:UIControlStateNormal];
    
    
    self.image = resultImage;
    //    self.shoppicImage.image = resultImage;
    //    self.headImg.image = resultImage;
    [_headImg setImage:resultImage forState:UIControlStateNormal];
    
}

#pragma mark - 2.UIImagePickerController的委托

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        STPhotoKitController *photoVC = [STPhotoKitController new];
        [photoVC setDelegate:self];
        [photoVC setImageOriginal:imageOriginal];
        
        [photoVC setSizeClip:CGSizeMake(_headImg.frame.size.width*4, _headImg.frame.size.width*4)];
        
        
        [self presentViewController:photoVC animated:YES completion:nil];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}
- (void)dismissContactView {
    [grayView removeFromSuperview];
}

#pragma mark - ---------- 懒加载 ----------
- (ICN_HeadImageSelView *)changeHeadImageView {
    if (!_changeHeadImageView)
    {
        _changeHeadImageView = [[NSBundle mainBundle] loadNibNamed:@"ICN_HeadImageSelView" owner:self options:nil].lastObject;
    }
    return _changeHeadImageView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
